package com.github.lzyzsd.jsbridge;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.RequiresApi;

import com.github.lzyzsd.webview.WebJSResourceIntercept;
import com.leadbank.baselbf.log.LogBus;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * Created by bruce on 10/28/15.
 */
public class BridgeWebViewClient extends WebViewClient {
    private String Tag = "BridgeWebViewClient";
    private BridgeWebView webView;
    private WebJSResourceIntercept webJSResourceIntercept = null;
    private WebJSLoadPage webJSLoadPage = null;
    private Context context;
    public BridgeWebViewClient(Context context,BridgeWebView webView, WebJSResourceIntercept webJSResourceIntercept, WebJSLoadPage webJSLoadPage) {
        this.webView = webView;
        this.context =context;
        this.webJSResourceIntercept = webJSResourceIntercept;
        this.webJSLoadPage = webJSLoadPage;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        try {
            LogBus.d(Tag,"shouldOverrideUrlLoading url = "+ url);
            //5.4.0添加
            if (url.contains("weixin://")) { // 打开微信
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                try {
                    context.startActivity(intent);
                } catch (Exception e) {
                }
                return true;
            }

            //5.4.0
            if (url.contains("alipays://")) { // 打开支付宝
                Uri uri = Uri.parse(url);
                Intent intent = new  Intent(Intent.ACTION_VIEW, uri);
                try {
                    context.startActivity(intent);
                } catch (Exception e) {
                }
                return true;
            }
//            //5.5.1 添加
//            if (url.contains("tel:")) { // 打电话
//                if(context instanceof Activity){
//                    WebAppUtils.callPhone((Activity) context, url);
//                }
//
//                return true;
//            }

            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (url.startsWith(BridgeUtil.YY_RETURN_DATA)) { // 如果是返回数据
            webView.handlerReturnData(url);
            return true;
        } else if (url.startsWith(BridgeUtil.YY_OVERRIDE_SCHEMA)) { //
            webView.flushMessageQueue();
            return true;
        } else if (url.startsWith(BridgeUtil.WV_JB_SCHEME)) { //
            return true;
        }else {
            return super.shouldOverrideUrlLoading(view, url);
//            view.loadUrl(url);
//            return false;
        }
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        LogBus.d(Tag,"onPageStarted = "+url);
//        if(webJSLoadPage != null){
//            LogBus.i(Tag,"onPageStarted 不为空 ");
//            webJSLoadPage.pageStarted(view,url);
//        }
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        LogBus.d(Tag,"onPageFinished = "+url);
        view.getSettings().setBlockNetworkImage(false);
        if (BridgeWebView.toLoadJs != null) {
            BridgeUtil.webViewLoadLocalJs(view, BridgeWebView.toLoadJs);
        }

        //
        if (webView.getStartupMessage() != null) {
            for (Message m : webView.getStartupMessage()) {
                webView.dispatchMessage(m);
            }
            webView.setStartupMessage(null);
        }
//        if (webJSLoadPage != null) {
//            webJSLoadPage.onPageFinished(view, url);
//        }
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        if (webJSResourceIntercept != null) {
            //拦截核心资源
            if (webJSResourceIntercept.interceptH5ResourceLib()) {
                return webJSResourceIntercept.getResourceLib(request.getUrl().toString());
            }
            //拦截非核心资源
            if (webJSResourceIntercept.interceptH5Resource()) {
                return webJSResourceIntercept.getResource(request.getUrl().toString());
            }

        }
        return super.shouldInterceptRequest(view, request);
    }


    @Override
    public void onLoadResource(WebView view, String url) {
//        LogBus.d(Tag,"onLoadResource url = "+ url);
        super.onLoadResource(view, url);
    }

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            LogBus.e(Tag, "VERSION_CODES.M23 onReceivedError ================ " + request.getUrl() + " " + error.getErrorCode() + " " + error.getDescription() + "<>" + view.getUrl());
//        }
        //99f237ec-f8ad-4cca-93cd-dafb786e40a6
        //增加 check 判断 webview 对象是否为空 加载的页面是否为空   空 进入错误页面
        // 如果页面加载的URL 和请求的URL 不是一致的不处理错误信息  一致的时候才处理显示错误界面
        //3.6.2 chen 修改 null 判断异常
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

                if ((view != null || view.getUrl() != null || !view.getUrl().equals("")) &&
                        request.getUrl() != null && !request.getUrl().toString().equals("") &&
                        request.getUrl().toString().equals(view.getUrl())) {
                    view.loadUrl("file:///android_asset/h5/webview_error.html");
                    if (webJSResourceIntercept != null) {
                        webJSResourceIntercept.webError();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
        super.onReceivedHttpError(view, request, errorResponse);
        LogBus.d(Tag,"onReceivedHttpError ");
    }

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        super.onReceivedSslError(view, handler, error);
        LogBus.d(Tag,"onReceivedSslError ");
//        // 接受所有网站的证书，忽略SSL错误，执行访问网页
//        handler.proceed();
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        LogBus.d(Tag,"onReceivedError ");
    }
}
